package com.github.niefy.modules.wx.service.impl;

import com.github.niefy.config.TaskExcutor;
import com.github.niefy.modules.wx.bo.ThirdSubMsg;
import com.github.niefy.modules.wx.entity.SubTemplateMsgLog;
import com.github.niefy.modules.wx.service.SubTemplateMsgLogService;
import com.github.niefy.modules.wx.service.SubTemplateMsgService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author liuxy
 * @date 2023-1-11
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SubTemplateMsgServiceImpl implements SubTemplateMsgService {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    private final SubTemplateMsgLogService SubTemplateMsgLogService;
    private final WxMpService wxService;
//    private final MsgTemplateService msgTemplateService;
//    private final WxUserService wxUserService;

    /**
     * 发送订阅通知  消息,使用固定线程的线程池
     */
    @Override
    @Async("taskExecutor")
    public void sendSubTemplateMsg(ThirdSubMsg thirdSubMsg) {
        TaskExcutor.submit(() -> {
            String result = "ok";
            try {
                wxService.switchover(thirdSubMsg.getAppid());
                wxService.getSubscribeMsgService().send(thirdSubMsg.getMsg());
            } catch (WxErrorException e) {
                result = e.getMessage();
                logger.info(result);
            }

            //保存发送日志
            SubTemplateMsgLog log = new SubTemplateMsgLog(thirdSubMsg.getMsg(), thirdSubMsg.getThirdId(), thirdSubMsg.getAppid(), result);
            SubTemplateMsgLogService.addLog(log);
        });
    }

    /**
     * 批量发送订阅通知  需要先进行消息的拼装
     */
    @Override
    @Async("taskExecutor")
    public void sendSubTemplateMsgBatch(List<ThirdSubMsg> thirdSubMsgList) {
        thirdSubMsgList.forEach(this::sendSubTemplateMsg);
    }

}
